<template>
  <div ref="chart"></div>
</template>

<script>
import echarts from "echarts";
import debounce from "debounce";
import { addListener, removeListener } from "resize-detector";
export default {
  name: "Chart",
  props: {
    options: {
      type : Object,
      default: () => {}
    }
  },
  watch: {
    options(newVal) {
      // this.chart.setOption(newVal, true)  // 或者 this.chart.clear()
      this.chart.clear()
      this.chart.setOption(newVal)
    }
  },
  created() {
    this.resize = debounce(this.resize, 200)
  },
  mounted() {
    addListener(this.$refs.chart, this.resize)
    this.renderChart()
  },
  beforeDestroy() { // 销毁组件Hooks
    removeListener(this.$refs.chart, this.resize)
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    resize() {
      this.chart.resize()
    },
    renderChart() {
      this.chart = echarts.init(this.$refs.chart)
      this.chart.setOption(this.options)
    }
  }
}
</script>
